package sifApp.SifAppActivity;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sifApp.FaceBookSDK.AsyncFacebookRunner;
import sifApp.FaceBookSDK.AsyncFacebookRunner.RequestListener;
import sifApp.FaceBookSDK.FacebookError;
import sifApp.PullToRefreshListView.PullToRefreshListView;
import sifApp.SifAppEntity.Friends;
import sifApp.korovyansk.android.slideout.SlideoutActivity;
import sifApp.sifAppStatic.FacebookObjects;
import sifApp.sifAppStatic.SaveData;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MyFriendActivity extends Activity {

	AsyncFacebookRunner asyncFbRunner;
	List<Friends> friendObjects;
	List<Bitmap> friendAvatarObjects;
	PullToRefreshListView pullToRefreshListView;
	MyArrayAdapter myArrayAdapter;
	
	int offset = 0;
	boolean isLoadMore = false;
	int friendsTotal = 0;
	
	public final int LOADING_FRIEND_LIST = 1;
	public final int LOADING_MORE_FRIEND_LIST = 2;
	
	FacebookObjects fbObjects;
	FrameLayout progressDialog;
	
	public void initComponents(){
		progressDialog = (FrameLayout) findViewById(R.id.layoutProgressDialog);
		fbObjects = FacebookObjects.getFacebookObjects();
		
		//Fly out menu
		findViewById(R.id.sample_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
						SlideoutActivity.prepare(MyFriendActivity.this, R.id.inner_content, width);
						startActivity(new Intent(MyFriendActivity.this,
								MenuActivity.class));
						overridePendingTransition(0, 0);
					}
				});
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friends_list);
		
		//init components
		initComponents();
		
		progressDialog.setVisibility(View.VISIBLE);
		
		asyncFbRunner = fbObjects.getAsyncRunner();
				
		friendObjects = new ArrayList<Friends>();
		friendAvatarObjects = new ArrayList<Bitmap>();
				
		pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_to_refresh_listview);						
		
		getFriendsCount();
		getFriendsPaging();
		
		pullToRefreshListView.setOnRefreshListener(new sifApp.PullToRefreshListView.PullToRefreshListView.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				if(offset > -1){
					offset+= 5;
					if(offset >= 5){
						isLoadMore = true;
					}
					getFriendsPaging();
				}				
				// Your code to refresh the list contents goes here

				// Make sure you call listView.onRefreshComplete()
				// when the loading is done. This can be done from here or any
				// other place, like on a broadcast receive from your loading
				// service or the onPostExecute of your AsyncTask.

				// For the sake of this sample, the code will pause here to
				// force a delay when invoking the refresh
				pullToRefreshListView.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						pullToRefreshListView.onRefreshComplete();
					}
				}, 0);
			}
		});

	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (msg.what == LOADING_FRIEND_LIST) {
				progressDialog.setVisibility(View.GONE);
				Log.i("load list friends", "Prepare");

				if (friendObjects.size() > 0) {
					Log.i("load list friends", "OK");
					myArrayAdapter = new MyArrayAdapter(
							MyFriendActivity.this, R.layout.row_friends_list,
							friendObjects);
					pullToRefreshListView.setAdapter(myArrayAdapter);
				}
			} 
			else if (msg.what == LOADING_MORE_FRIEND_LIST) {
				if (friendObjects.size() > 0) {
					myArrayAdapter.notifyDataSetChanged();
				}
			}
		}

	};
	
	
	
	class MyArrayAdapter extends ArrayAdapter<Friends> {

		public MyArrayAdapter(Context context, int textViewResourceId) {
			super(context, textViewResourceId);
			// TODO Auto-generated constructor stub
		}

		public MyArrayAdapter(Context context, int textViewResourceId,
				List<Friends> objects) {
			super(context, textViewResourceId, objects);
			// TODO Auto-generated constructor stub
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View v = convertView;
			if (v == null) {
				LayoutInflater inflater = getLayoutInflater();
				v = inflater.inflate(R.layout.row_friends_list, null);
			}
			TextView tvName = (TextView) v.findViewById(R.id.tvFriendName);
			tvName.setText(this.getItem(position).name);
			ImageView ivAvatar = (ImageView) v
					.findViewById(R.id.ivFriendAvatar);
						
			try {
				if(friendAvatarObjects.get(position) != null){
					ivAvatar.setImageBitmap(friendAvatarObjects.get(position));
				}	
			} catch (Exception e) {
				Log.i("thaile", "error : outofarraybound" + e.toString());
				ivAvatar.setImageResource(android.R.drawable.star_on);
			}
					
			return v;
		}

	}
	
	/*
	 * get Friends Total Count
	 */
	public void getFriendsCount() {
		fbObjects.getAsyncRunner().request("me/friends", new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Friends", response);
				String json = response;
				try {
					// Facebook Profile JSON data
					JSONObject json_response = new JSONObject(json);

					final String return_json = json_response.toString();
					Log.i("return json", return_json);

					JSONArray arr = json_response.getJSONArray("data");
					friendsTotal = arr.length();			

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}

		});
	}
	
	/**
	 * get your friends list
	 * */
	public void getFriendsPaging() {
		Bundle params = new Bundle();
		params.putString("limit", "5");
		params.putString("offset", "" + offset);

		fbObjects.getAsyncRunner().request("me/friends", params, new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Friends", response);
				String json = response;
				try {
					// Facebook Profile JSON data
					JSONObject json_response = new JSONObject(json);

					final String return_json = json_response.toString();
					Log.i("return json", return_json);

					JSONArray arr = json_response.getJSONArray("data");
					if(arr.length() > 0){
						for (int i = 0; i < arr.length(); i++) {
							JSONObject obj = arr.getJSONObject(i);
							Log.i("name", obj.getString("name"));
							friendObjects.add(new Friends(obj.getString("id"), 
									SaveData.getInstance(getApplicationContext()).getMyAccountId(), 
									obj.getString("name"), 
									"https://graph.facebook.com/"
											+ obj.getString("id") + "/picture"));
							URL img_url = null;
							Bitmap avatar = null;
							try {
								img_url = new URL("https://graph.facebook.com/"
										+ obj.getString("id") + "/picture");
								try {
									avatar = BitmapFactory.decodeStream(img_url
											.openConnection().getInputStream());
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								friendAvatarObjects.add(avatar);
								
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}						
						friendsTotal-= 5;
						if(friendsTotal <= 0){
							//Neu da load het thi ngung ko load nua
							offset = -1;
						}
						if(isLoadMore){
							handler.sendEmptyMessage(LOADING_MORE_FRIEND_LIST);
						}
						else{
							handler.sendEmptyMessage(LOADING_FRIEND_LIST);
						}
					}				
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});

	}
}
